package com.camin.android;

import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TableRow;

import com.camin.android.adapters.RecipeAdapter;
import com.camin.android.utils.Constants;

public class RecipeListActivity extends BaseActivity {

	private boolean showSearch = false;

	private ListView getListView()	{
		return (ListView)findViewById(R.id.lvRecipes);
	}
	
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.recipe_list);

		refreshListItems();
		
		Button btnSearch = (Button) findViewById(R.id.btnSearchRecipe);
		btnSearch.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v) {
				showSearch = !showSearch;
				showSearchTextBox();
			}
		});

		Button btnAddRecipe = (Button) findViewById(R.id.btnAddRecipe);
		btnAddRecipe.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent(getBaseContext(),
						RecipeActivity.class);
				startActivityForResult(intent, 0);

			}
		});

		EditText editSearch = (EditText) findViewById(R.id.editSearchRecipeName);
		editSearch.setOnKeyListener(new Button.OnKeyListener() {
			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {

				if (keyCode == KeyEvent.KEYCODE_ENTER) {
					Intent intent = new Intent(getBaseContext(),
							IngredientListActivity.class);
					startActivityForResult(intent, 0);
				}
				return false;
			}
		});

		showSearchTextBox();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK)
		{
			refreshListItems();
	        
			Bundle extras = data.getExtras();
			if (extras != null) {
				long id = extras.getLong(Constants.RECIPE_ID, -1l);
				getListView().setSelection((int)id);
			}
	        
		}
		super.onActivityResult(requestCode, resultCode, data);
	}
	
	private void refreshListItems()
	{
		Cursor recipesCursor = getDataHelper().getAllRecipes(getDatabase());
		recipesCursor.moveToFirst();
		
		RecipeAdapter adapter = new RecipeAdapter(this, recipesCursor);
		getListView().setAdapter(adapter);	
		getDatabase().close();
	}

	
	private void showSearchTextBox() {
		TableRow trSearchRecipe = (TableRow) findViewById(R.id.trSearchRecipeRow);
		if (showSearch == true) {
			trSearchRecipe.setVisibility(View.VISIBLE);
		} else {
			trSearchRecipe.setVisibility(View.INVISIBLE);
		}
	}

}